package com.example.waterorder.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponseBody;
import com.aliyun.tea.*;

import com.example.waterorder.entity.IdCardEntity.BaseStr;
import com.example.waterorder.entity.IdCardEntity.IdCardRoot;
import com.example.waterorder.tools.ImageUtil;
import com.example.waterorder.tools.OcrTool;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Slf4j
@RestController
@RequestMapping("/Id")
public class IdController {

//    @SneakyThrows
    @PostMapping("/ocr")
    @Operation(summary = "接收图片base64编码 进行身份证识别")
    public Object ocr(@RequestBody BaseStr baseStr) throws Exception {
        log.info("here");
//        System.out.println(baseStr.getBaseStr());
        com.aliyun.ocr_api20210707.Client client = OcrTool
                .createClient("LTAI5t9DwLyXfrjaSD5FDuA3", "SkVYivVK9sn3RszPXshNljBoADeqm5");
        // 需要安装额外的依赖库，直接点击下载完整工程即可看到所有依赖。
        InputStream bodySyream = ImageUtil.base2InputStream(baseStr.getBaseStr());
        com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest recognizeIdcardRequest = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest()
                .setBody(bodySyream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);
            RecognizeIdcardResponseBody body = response.getBody();
            String data = body.getData();
            System.out.println(data);
//            System.out.println(JSON.parseObject(data, IdCardRoot.class));
            return JSON.parseObject(data, IdCardRoot.class);
        } catch (TeaException error) {
            // 打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return null;
    }
}